//
//  XYThirdthStepViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/9.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "XYThirdthStepViewController.h"
#import "XYFourthStepViewController.h"
#import "ServiceUser.h"

@interface XYThirdthStepViewController ()<UITextFieldDelegate>

@end

@implementation XYThirdthStepViewController

static const NSString * KEY_STEP  = @"step3";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"setp3 record === %@", self.NewRecordArray.firstObject.getDetailDict);
    [self setNaviBarTitle:self.NewRecordArray.firstObject.name];
    _contentTableView = [[UITableView alloc] initWithFrame:
                         CGRectMake(10, fHeight_Nav + fHeight_StatueBar + 10, fWidth_Current - 20, fHeight_Current - fHeight_Nav - fHeight_StatueBar - 60)];
    _contentTableView.backgroundColor = [UIColor clearColor];
    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _contentTableView.dataSource = self;
    _contentTableView.delegate = self;
    [self.view addSubview:_contentTableView];
    timeArr=[[NSMutableArray alloc]init];
    nameArr=[[NSMutableArray alloc]init];
    numberArr=[[NSMutableArray alloc]init];

    UIImageView*buttomview = [[UIImageView alloc]initWithFrame:CGRectMake(0, fHeight_Current - 50, fWidth_Current, 50)];
    buttomview.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    [self.view addSubview:buttomview];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 50)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:14];
    label.textColor=[UIColor lightGrayColor];
    label.text=@"当下是第三步3/6";
    [buttomview addSubview:label];
    for (Record *nowRecord in self.NewRecordArray) {
        NSString*timestr=@"";
        NSString*nameStr=@"";
        NSString*NumberStr=@"";
        NSMutableDictionary*userDic=[[NSMutableDictionary alloc]init];
        if ([[nowRecord getDetailDict] objectForKey:KEY_STEP] &&
            [[[nowRecord getDetailDict] objectForKey:KEY_STEP] count] > 0 &&
            [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:0] objectForKey:KEY_RECORD_ANSWER]) {
            timestr = [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:0] objectForKey:KEY_RECORD_ANSWER];
        }
        if ([[nowRecord getDetailDict] objectForKey:KEY_STEP] &&
            [[[nowRecord getDetailDict] objectForKey:KEY_STEP] count] > 1 &&
            [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:1] objectForKey:KEY_RECORD_ANSWER]) {
            nameStr = [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:1] objectForKey:KEY_RECORD_ANSWER];
        }
        if ([[nowRecord getDetailDict] objectForKey:KEY_STEP] &&
            [[[nowRecord getDetailDict] objectForKey:KEY_STEP] count] > 2 &&
            [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:2] objectForKey:KEY_RECORD_ANSWER]) {
            NumberStr = [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:2] objectForKey:KEY_RECORD_ANSWER];

        }
        [nameArr addObject:nameStr];
        [numberArr addObject:NumberStr];
        [timeArr addObject:timestr];
    }
   
}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0||section==1) {
        return 1+self.NewRecordArray.count;

    }else{
        return 1;

    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;//返回标题数组中元素的个数来确定分区的个数
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return 60;
        }else{
            return 90;
        }

    }else if (indexPath.section==1) {
        if (indexPath.row==0) {
            return 60;
        }else{
            return 120+30;
        }
        
    }else {
        return 60;

    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *strIdentifier = [NSString stringWithFormat:@"strIdentifier%ld",(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];
    
    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:strIdentifier];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            UILabel *titlelab = [[UILabel alloc]initWithFrame:
                                 CGRectMake(10, 0, fWidth_Current - 40, 60)];
            titlelab.textColor=[UIColor whiteColor];
            titlelab.backgroundColor=[UIColor clearColor];
            titlelab.text=@"3.1、抽血日期和时间";
            [cell addSubview:titlelab];
            
            UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 59, fWidth_Current-20, 1)];
            lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
            [cell addSubview:lineview];
        }else{
            Record*nowrecord=[self.NewRecordArray objectAtIndex:indexPath.row-1];
            UILabel*recordNameLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, fWidth_Current, 30)];
            recordNameLab.backgroundColor=[UIColor clearColor];
            recordNameLab.textColor=[UIColor whiteColor];
            recordNameLab.font=[UIFont systemFontOfSize:16];
            recordNameLab.text=[NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
            [cell addSubview:recordNameLab];
            NSString*timestr=[timeArr objectAtIndex:indexPath.row-1];
            UILabel * timeLab = [[UILabel alloc]initWithFrame:
                                 CGRectMake(10, 30, tableView.frame.size.width - 52, 60)];
            timeLab.backgroundColor = [UIColor clearColor];
            timeLab.textColor = [UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            [cell addSubview:timeLab];
            timeLab.text=timestr;
            
            UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(fWidth_Current-20-70, 18+30, 60, 25)];
            btn1.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn1.layer.cornerRadius=10;
            [btn1 setTitle:@"开始采血" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(reloadtime1:) forControlEvents:UIControlEventTouchUpInside];
            btn1.titleLabel.font=[UIFont systemFontOfSize:11];
            btn1.clipsToBounds=YES;
            btn1.tag=indexPath.row-1;
            [cell addSubview:btn1];
            
            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                btn1.hidden = YES;
            }else{
                btn1.hidden = NO;
            }
        }
        
    }else if(indexPath.section==1){
        if (indexPath.row==0) {
            NSString*titlestr=@"3.2、抽血者信息";
            
            UILabel *titlelab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, fWidth_Current-40, 60)];
            titlelab.textColor=[UIColor whiteColor];
            titlelab.backgroundColor=[UIColor clearColor];
            titlelab.text=titlestr;
            titlelab.numberOfLines=0;
           
            
            UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0,59, fWidth_Current-20, 0.5)];
            lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
            [cell addSubview:titlelab];
            [cell addSubview:lineview];
        }else{
            Record*nowrecord=[self.NewRecordArray objectAtIndex:indexPath.row-1];
            UILabel*recordNameLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, fWidth_Current, 30)];
            recordNameLab.backgroundColor=[UIColor clearColor];
            recordNameLab.textColor=[UIColor whiteColor];
            recordNameLab.font=[UIFont systemFontOfSize:16];
            recordNameLab.text=[NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
            [cell addSubview:recordNameLab];
            
            UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(fWidth_Current-20-60,10, 50, 25)];
            btn1.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn1.layer.cornerRadius=10;
            [btn1 setTitle:@"选择" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(gotoselectmenber:) forControlEvents:UIControlEventTouchUpInside];
            btn1.titleLabel.font=[UIFont systemFontOfSize:11];
            btn1.clipsToBounds=YES;
            btn1.tag=indexPath.row-1;
            [cell addSubview:btn1];
            NSString*namestr=[nameArr objectAtIndex:indexPath.row-1];
            NSString*numberstr=[numberArr objectAtIndex:indexPath.row-1];
            
            UILabel*firstlabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 30, 60, 60)];
            firstlabel.backgroundColor=[UIColor clearColor];
            firstlabel.textColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            [cell addSubview:firstlabel];
            firstlabel.text=@"姓名：";
            UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0,89, fWidth_Current-20, 0.5)];
            lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
            [cell addSubview:lineview];
            UILabel*secondlabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 90, 60, 60)];
            secondlabel.backgroundColor=[UIColor clearColor];
            secondlabel.textColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            [cell addSubview:secondlabel];
            secondlabel.text=@"工号：";
            UIImageView*lineview2=[[UIImageView alloc]initWithFrame:CGRectMake(0,149, fWidth_Current-20, 0.5)];
            lineview2.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
            [cell addSubview:lineview2];
            
            UITextField* usernamefiled=[[UITextField alloc]initWithFrame:CGRectMake(10+55,30, fWidth_Current-40-55, 60)];
            usernamefiled.backgroundColor=[UIColor clearColor];
            usernamefiled.textColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            usernamefiled.placeholder=@"";
            [cell addSubview:usernamefiled];
            usernamefiled.text=namestr;
            usernamefiled.returnKeyType = UIReturnKeyDone;//变为搜索按钮
            
            usernamefiled.delegate = self;//设置代理
            
            UITextField*usernumberfiled=[[UITextField alloc]initWithFrame:CGRectMake(10+55, 90, fWidth_Current-40-55, 60)];
            usernumberfiled.textColor=[UIColor whiteColor];
            usernumberfiled.backgroundColor=[UIColor clearColor];
            usernumberfiled.textColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            usernumberfiled.placeholder=@"";
            [cell addSubview:usernumberfiled];
            usernumberfiled.text=numberstr;
            usernamefiled.tag=10000+indexPath.row-1;
            usernumberfiled.returnKeyType = UIReturnKeyDone;//变为搜索按钮
            usernumberfiled.tag=100000+indexPath.row-1;

            usernumberfiled.delegate = self;//设置代理
            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                usernumberfiled.userInteractionEnabled = NO;
                usernamefiled.userInteractionEnabled = NO;
                
            }else{
                usernumberfiled.userInteractionEnabled = YES;
                usernamefiled.userInteractionEnabled = YES;
                
            }
        }
        
    }else{
        cell.backgroundColor=[UIColor clearColor];
        UIView *footerView = [[UIView alloc] initWithFrame:
                              CGRectMake(0, 0, tableView.frame.size.width , 50)];
        footerView.backgroundColor = [UIColor clearColor];
        
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            
            UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 10, footerView.frame.size.width, 50)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"下一步" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            [cell addSubview:footerView];
        }else{
            
            UIButton *btn1=[[UIButton alloc]initWithFrame:
                            CGRectMake(0, 10, (footerView.frame.size.width - 10) / 2, 50)];
            btn1.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
            btn1.layer.cornerRadius=5;
            [btn1 setTitle:@"取消" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
            btn1.clipsToBounds=YES;
            [footerView addSubview:btn1];
            UIButton *btn2=[[UIButton alloc]initWithFrame:
                            CGRectMake(btn1.frame.origin.x + btn1.frame.size.width + 10,
                                       btn1.frame.origin.y,
                                       btn1.frame.size.width, btn1.frame.size.height)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"保存" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            [cell addSubview:footerView];
        }

    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 10;
}

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *footerView = [[UIView alloc] initWithFrame:
                          CGRectMake(0, 0, tableView.frame.size.width , 10)];
    footerView.backgroundColor = [UIColor clearColor];
    return footerView;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            
        }else{
            return;
            if (!_datePickAlertVC) {
                _datePickAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
                //初始化一个标题为“选择时间”，风格是ActionSheet的UIAlertController，其中"\n"是为了给DatePicker腾出空间
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    //点击确定按钮的事件处理
                    _dateLabel.text = [self dateToString:_datePicker.date];
                }];
                
                _datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker
                _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
                [_datePickAlertVC.view addSubview:_datePicker];//将datePicker添加到UIAlertController实例中
                [_datePickAlertVC addAction:cancel];//将确定按钮添加到UIAlertController实例中
            }
            [self presentViewController:_datePickAlertVC animated:YES completion:^{
            }];//通过模态视图模式显示UIAlertController，相当于UIACtionSheet的show方法
        }
    }
    
}
-(void)gotoselectmenber:(UIButton *)sender{
    MamberselectViewController *MamberselectVC= [[MamberselectViewController alloc] init];
    MamberselectVC.delegate=self;
    MamberselectVC.nowIndex=sender.tag;
    [self presentViewController:MamberselectVC animated:YES completion:nil];
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    long count=textField.tag-100000;
    if (count<0) {
        //name
        long counts=textField.tag-10000;
        [nameArr replaceObjectAtIndex:counts withObject:textField.text];

    }else{
        //number
        [numberArr replaceObjectAtIndex:count withObject:textField.text];

    }
}
#pragma mark - MenberselectDelegate
-(void)Manberselectfinished:(MamberselectViewController *)MamberselectViewController withmenberarr:(NSMutableArray *)menberarr withIndex:(NSInteger)index{
    ServiceUser *tempUser = (ServiceUser *)[menberarr objectAtIndex:0];
    NSString *name1=tempUser.displayname;
    NSString *name2=tempUser.username;
    [nameArr replaceObjectAtIndex:index withObject:name1];
    [numberArr replaceObjectAtIndex:index withObject:name2];

    [_contentTableView reloadData];
 
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)reloadtime1:(UIButton *)sender{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    [timeArr replaceObjectAtIndex:sender.tag withObject:dateString];
    [_contentTableView reloadData];
}
-(void)saveClick{

    for (int i=0;i<timeArr.count;i++) {
        NSString*str=[timeArr objectAtIndex:i];
        if ([str isEqualToString:@""]) {
            Record*nowrecord=[self.NewRecordArray objectAtIndex:i];
            NSString*msg=[NSString stringWithFormat:@"请选择样本%@的采集日期！",nowrecord.recordId];
            [self.view makeToast:msg];
            return;
        }
    }

    [self creatDetailDict];

    
    XYFourthStepViewController *XYFourthStepVC = [[XYFourthStepViewController alloc] init];
//    XYFourthStepVC.record = self.record;
    XYFourthStepVC.NewRecordArray=self.NewRecordArray;
    [self.navigationController pushViewController:XYFourthStepVC animated:YES];
}
-(void)cancelclick{
    UIViewController*miloViewControl=(UIViewController *)[[self.navigationController viewControllers]objectAtIndex:1];
    [self.navigationController popToViewController:miloViewControl animated:YES];
}
- (NSString *)dateToString:(NSDate *)date {
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+0800"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    
    [formatter setTimeZone:timeZone];
    
    NSString * timeString = [formatter stringFromDate:date];
    
    return timeString;
}

-(void)creatDetailDict{
    for (Record *oneRecord in self.NewRecordArray) {
        NSInteger index =[self.NewRecordArray indexOfObject:oneRecord];
        NSString *timestr=[timeArr objectAtIndex:index];
        NSString *userStr=[nameArr objectAtIndex:index];
        NSString *numberStr=[numberArr objectAtIndex:index];
        NSDictionary *questionDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"3.1、抽血日期和时间", KEY_RECORD_QUESTION,
                                      TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                      timestr, KEY_RECORD_ANSWER, nil];
        NSDictionary *question2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                       @"3.2、抽血者姓名", KEY_RECORD_QUESTION,
                                       TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                       userStr, KEY_RECORD_ANSWER, nil];
        NSDictionary *question3Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                       @"3.3、抽血者工号", KEY_RECORD_QUESTION,
                                       TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                       numberStr, KEY_RECORD_ANSWER, nil];
        
        NSArray *qustionArr = [NSArray arrayWithObjects:questionDict,question2Dict,question3Dict, nil];
        NSMutableDictionary *tempDict = [oneRecord getDetailDict];
        [tempDict setObject:qustionArr forKey:KEY_STEP];
        [oneRecord setDetailDict:tempDict];
        oneRecord.recordDetail = [tempDict JSONString];
        oneRecord.savedStepCount = 3;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [oneRecord update];
        });
    }

   
    
   

}

-(void)nextStepClick{
    XYFourthStepViewController *XYFourthStepVC = [[XYFourthStepViewController alloc] init];
//    XYFourthStepVC.record = self.record;
    XYFourthStepVC.NewRecordArray=self.NewRecordArray;
    XYFourthStepVC.fromtype = @"search";
    [self.navigationController pushViewController:XYFourthStepVC animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField

{
    
    [self.view endEditing:YES];
    return YES;
    
}
@end
